<?php

class Core_Component_Cms_Controller_Backend_Category{
    
    public function __construct() {
        $GLOBALS[RC]->getHelper()->setLocation('{cms.cms_menu}', '{cms.category_menu}');
    }
    
    public function mappingAction(){
        return array(
            'create'=>'edit'
        );
    }
    
    public function contentsAjaxAction($id){
        $list = App::getModel('cms/category')
                    ->loadBy(array('id'=>$id, 'website_id'=>App::getRunningWebsite()->getId()))
                    ->getContents()
                    ->select('`m`.`id`, `v`.`title`')
                    ->fetch()
                    ->toArray();
        return $GLOBALS[RC]->getHelper()->jsonResult()->setData('contents', $list);
    }    
    
    public function indexAction($pageindex = 1, $pagesize = 20){
        $q = App::getModel('cms/category')->getQuery();
        $list = $q->pagination($pageindex, $pagesize)->fetch();
        $count = $q->fetchCount();
        return $GLOBALS[RC]->getHelper()->templateResult(array('list' => $list, 'record_count' => $count));
    }    
    
    public function editAction($id = NULL) {
        $model = App::getModel('cms/category');
        if (!is_null($id)) {
            $model->load($id);
            $categories = App::getModel('cms/category')
                            ->getQuery()
                            ->condition('v.website_id', App::getRunningWebsite()->getId())
                            ->condition('v.version_id', $id, 'neq')
                            ->fetch();
            $GLOBALS[RC]->getHelper()->setLocation($model->getName());
        }else{
            $categories = App::getModel('cms/category')
                            ->getQuery()
                            ->condition('v.website_id', App::getRunningWebsite()->getId())
                            ->fetch();
            $GLOBALS[RC]->getHelper()->setLocation('{cms.create_category}');
        }
        return $GLOBALS[RC]->getHelper()->modelFormResult($model,
                array('parent_id'=>array('data'=>$categories->toArray(), 'labelKey'=>'name', 'valueKey'=>'id')),
                '*/*/edit');
    }    
    
    public function saveAction(Core_Component_Cms_Model_Category $model) {
        $model->merge()->validate()->save();
        $GLOBALS[RC]->getMessager()->addSuccess('{system.message.success}');
        return $GLOBALS[RC]->getHelper()->historyResult('*/*/*/index');
    }
    
    public function deleteAction($id) {
        App::loadModel('cms/category', $id)->delete();
        $GLOBALS[RC]->getMessager()->addSuccess('{system.message.success}');
        return $GLOBALS[RC]->getHelper()->historyResult('*/*/*/index');
    }    
}